/**
 * Copyright (C) 2009 Noel Ang
 *
 * This file is part of Samsara.
 *
 * Samsara is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Samsara is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Samsara.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.lunarshades.samsara.ui.actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.net.URL;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

/**
 * Action for inverting the row selection in a table.
 *
 * @author Noel Ang, sparta.variable@gmail.com
 */
public class SelectInvertAction extends AbstractAction {

public SelectInvertAction(JTable table) {
    super(NAME);

    mTable = table;
    URL smallIconUrl = getClass().getResource(
            "/com/lunarshades/samsara/ui/icons/all_invert_small.png"
    );
//    URL largeIconUrl = getClass().getResource(
//            "/com/lunarshades/samsara/ui/icons/all.png"
//    );
    putValue(Action.SMALL_ICON, new ImageIcon(smallIconUrl));
//    putValue(Action.LARGE_ICON_KEY, new ImageIcon(largeIconUrl));
    putValue(Action.SHORT_DESCRIPTION, SHORT_TEXT);
    putValue(Action.MNEMONIC_KEY, KeyEvent.VK_V);
}

public void actionPerformed(ActionEvent e) {
    ListSelectionModel selectModel = mTable.getSelectionModel();
    int distance = Integer.MAX_VALUE;
    int leadRow = selectModel.getLeadSelectionIndex();
    int newLeadRow = -1;
    for (int i = 0, numRows = mTable.getRowCount(); i < numRows; ++i) {
        if (!selectModel.isSelectedIndex(i)) {
            selectModel.addSelectionInterval(i, i);

            int newDistance = Math.abs(i - leadRow);
            if (newDistance < distance) {
                distance = newDistance;
                newLeadRow = i;
            }
        } else {
            selectModel.removeIndexInterval(i, i);
        }
    }
    if (newLeadRow != -1) {
        mTable.changeSelection(newLeadRow, 0, false, false);
    }
}

private static final String NAME = "Invert Selection";
private static final String SHORT_TEXT = "Invert selection of table entries";
private final JTable mTable;
}
